<?php

/**
 * 类的介绍 ：微信工具类
 *
 * @param mixed
 * @return array 返回类型
 * @author      wh
 */


namespace App\Utils;


use App\Http\Controllers\WeChatMessageController;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Cache;
use phpDocumentor\Reflection\Types\This;
use function Symfony\Component\String\b;

class WechatUtils
{
    //微信ID
    public $app_id;
    //应用密匙
    private $secret;


    public function __construct()
    {
        $this->app_id = config('app.wx.wx_app_id');
        $this->secret = config('app.wx.wx_secret');
    }

    /**
     * 类的介绍 ：发送模板消息
     *
     * @Time 2020/8/27 15:19
     * @User  Mr.w
     * @param mixed ${arg1}
     */
    public function sendTemplate()
    {

    }

    /**
     * 类的介绍 ：发送消息
     *
     * @Time 2020/8/27 15:16
     * @User  Mr.w
     * @param $type
     * @param $openid
     * @param $data
     */
    public function sendMessage($type, $data)
    {
        $client = new Client();
        $msg = [];
        switch ($type) {
            case 1:
                $msg = ["touser" => $data["open_id"],
                    "msgtype" => "text",
                    "text" => ["content" => $data['content']]];
                //文本
                break;
            case 6:
                //图文信息
                $msg = [
                    "touser" => $data["open_id"],
                    "msgtype" => "news",
                    "news" => [
                        "articles" => [[
                            "title" => $data["title"],
                            "description" => $data["desc"],
                            "url" => $data["url"],
                            "picurl" => $data["picurl"]]
                        ]
                    ]
                ];
                break;

        }

        $res = $client->request('post', 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $this->getAccessToken()
            , [
                'body' => json_encode($msg, JSON_UNESCAPED_UNICODE)
            ]);
        $data = $res->getBody();
        info('sendMessage状态 => ' . $data);
        return $data;

    }


    /**
     * 类的介绍 ：获取微信公众号AccessToken
     *
     * @Time 2020/9/16 11:36
     * @User  Mr.w
     * @param mixed ${arg1}
     */
    public function getAccessToken()
    {
        $client = new Client();
        //从中获取缓存中有效的access_token
        $access_token = Cache::get('access_token');
        if ($access_token) {
            return $access_token;
        }
        $curl = $client->get('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this->app_id . '&secret=' . $this->secret);
        $data = json_decode($curl->getBody()->getContents());
        if (isset($data->errcode)) {
            info('获取access_token状态失败：' . $data->errmsg . '状态码：' . $data->errcode);
            $send_sms = new SmsUtils();
            $msg=[
                //错误码
                "code"=>$data->errcode,
                //错误信息
                "msg"=>$data->errmsg
            ];
            $send_sms->sendSms(config('app.wx.sms_access_key_id'), config('app.wx.sms_access_key_secret'), '18627923130', config('app.wx.sms_sign_name'), config('app.wx.sms_sys_template_code'), $msg);
            return null;
        }
        $access_token = $data->access_token;
        info('获取access_token成功！' . $access_token);
        //重新设置缓存，有效期120分钟
        Cache::put('access_token', $access_token, 7200);
        return $access_token;
    }

    /**
     * 类的介绍 ：获取jssdk签名所需jspapi_ticket
     *
     * @Time 2020/9/16 11:36
     * @User  Mr.w
     * @param mixed ${arg1}
     */
    public function getJsapiTicket()
    {
        $client = new Client();
        $jspapi_ticket = Cache::get('jspapi_ticket');
        if ($jspapi_ticket) {
            return $jspapi_ticket;
        }
        $curl = $client->get('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' . $this->getAccessToken() . '&type=jsapi');
        $data = json_decode($curl->getBody()->getContents());
        if ($data->errcode != 0) {
            info('获取getticket状态失败：' . $data->errmsg . '状态码：' . $data->errcode);
            return null;
        }
        $jspapi_ticket = $data->ticket;
        info('获取access_token成功！');
        //重新设置缓存，有效期120分钟
        Cache::put('jspapi_ticket', $jspapi_ticket, 7200);
        return $jspapi_ticket;

    }

    /**
     * 类的介绍 ：获取用户信息
     *
     * @Time 2020/9/16 11:51
     * @User  Mr.w
     * @param mixed ${arg1}
     */
    public function getUserInfo($open_id)
    {
        $client = new Client();
        $curl = $client->get('https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . $this->getAccessToken() . '&openid=' . $open_id . '&lang=zh_CN');
        $data = json_decode($curl->getBody()->getContents());
        if (isset($data->errcode)) {
            info('获取用户信息失败！：' . $data->errmsg . '状态码：' . $data->errcode);
            return null;
        }
        return $data;

    }


}
